from __future__ import annotations
from typing import List, Optional

from playwright.async_api import Page, TimeoutError as PlaywrightTimeoutError

from axiom_boot.logging.setup import get_logger
from axiom_boot.scraper.models import Target

# 添加以下导入
import os

logger = get_logger(__name__)
async def perform_login(page: Page, target: Target):
    """
    一个辅助函数，用于在 Made-in-China.com 执行登录操作。
    它会检查是否已登录，如果未登录，则使用提供的凭据进行登录。
    """
    login_url = "https://login.made-in-china.com/"
    logger.info(f"导航到登录页面: {login_url}")
    await page.goto(login_url, wait_until="networkidle")

    # 检查是否已经登录（例如，通过查找特定的“我的账户”元素）
    # 注意：这个选择器需要根据实际登录后的页面元素来确定
    my_account_selector = "div.my-account" 
    try:
        if await page.is_visible(my_account_selector, timeout=5000):
            logger.info("检测到已登录，跳过登录步骤。")
            # 登录后，重定向回主页以进行后续操作
            await page.goto("https://www.made-in-china.com/", wait_until="networkidle")
            return
    except Exception:
        logger.info("未检测到登录状态，继续执行登录流程。")

    credentials = target.metadata.get("credentials")
    if not credentials or "username" not in credentials or "password" not in credentials:
        logger.error("在 Target 元数据中未找到有效的登录凭据。")
        raise ValueError("缺少登录凭据。")

    username = credentials["username"]
    password = credentials["password"]

    # 定位输入框和按钮
    username_input_selector = "#logonVo_logonId"
    password_input_selector = "#logonVo_password"
    login_button_selector = "#logonVo_submit"

    logger.info(f"正在使用用户名 '{username}' 进行登录...")
    await page.fill(username_input_selector, username)
    await page.fill(password_input_selector, password)
    await page.click(login_button_selector)

    # 等待登录成功后的页面跳转或特定元素的出现
    # 比如，等待导航到主页或出现用户头像
    logger.info("已提交登录表单，等待登录成功后的页面加载...")
    try:
        # 等待导航到主页，这是一个比较可靠的登录成功信号
        await page.wait_for_url("https://www.made-in-china.com/**", timeout=30000)
        logger.info("登录成功！已跳转到主页。")
    except PlaywrightTimeoutError:
        logger.error("登录超时。可能原因：凭据错误、网络问题或出现验证码。")
        # 您可以在此处添加更复杂的错误处理，例如截图保存
        debug_path = "storage/debug"
        os.makedirs(debug_path, exist_ok=True)
        await page.screenshot(path=os.path.join(debug_path, "login_failed.png"))
        raise
        
async def perform_search(page: Page, target: Target):
    """一个辅助函数，用于在页面上执行搜索操作。"""
    keyword = target.metadata.get("search_keyword")
    search_type = target.metadata.get("search_type", "product")  # 默认为产品

    if not keyword:
        return

    logger.info(f"正在模拟搜索: 类型='{search_type}', 关键词='{keyword}'")

    if search_type == "supplier":
        dropdown_trigger_selector = ".nail-search-select .nail-ss-title"
        logger.info(f"等待并点击下拉菜单: {dropdown_trigger_selector}")
        await page.wait_for_selector(dropdown_trigger_selector, state="visible", timeout=15000)
        await page.click(dropdown_trigger_selector)

        supplier_option_selector = "dd.nail-search-option:has-text('Suppliers')"
        logger.info(f"等待并点击 'Suppliers' 选项: {supplier_option_selector}")
        await page.wait_for_selector(supplier_option_selector, state="visible", timeout=5000)
        await page.click(supplier_option_selector)

    input_selector = "input.nail-search-input"
    logger.info(f"在搜索框 {input_selector} 中填入关键词: '{keyword}'")
    await page.fill(input_selector, keyword)

    search_button_selector = "button.nail-search-btn"
    logger.info(f"点击搜索按钮: {search_button_selector}")
    await page.click(search_button_selector)

    # 修正等待策略：等待由您确认的、正确的供应商列表项选择器
    logger.info("等待供应商结果列表 (div.list-node) 出现...")
    await page.wait_for_selector("div.list-node", state="visible", timeout=30000)

    logger.info("搜索结果页面已加载。")


async def close_popups_if_present(page: Page, target: Target):
    """一个辅助函数，用于检测并关闭潜在的弹窗。"""
    popup_close_selectors = [
        ".J-campaign-pop-close",
        "div[class*='-dialog-'] .close",
        ".J-g-close", ".guid-close", ".ad-close-button", "div[class*='dialog'] a[class*='close']",
        '[aria-label="Close"]', '[aria-label="close"]',
        'button.close', 'a.close',
        '.btn-close', '.close-btn',
        '.mfp-close',
        '#fancybox-close',
        'div[class*="popup"] a[class*="close"]',
        'div[class*="modal"] button[class*="close"]'
    ]
    for selector in popup_close_selectors:
        try:
            close_button = page.locator(selector).first
            if await close_button.is_visible(timeout=1000):
                await close_button.click(timeout=2000)
                logger.info(f"成功关闭了一个弹窗: '{selector}'")
                return
        except PlaywrightTimeoutError:
            logger.debug(f"未找到或弹窗关闭按钮不可见: '{selector}'，继续...")
            pass 